package com.westa.smallshop.util.volley;

import android.text.TextUtils;

import com.android.volley.Request;
import com.westa.smallshop.util.Global;
import com.westa.smallshop.util.TokenUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Dune on 16/5/4.
 */
public class MyHttpClient {

    private static HashMap<String, String> mHeaders = new HashMap<>();

    public static void init() {
        mHeaders.clear();
        mHeaders.put(Global.SYSTEM_TAG, Global.SYSTEM_NAME);

    }

    public static HashMap<String, String> getHeaders(boolean hasToken) {

        if (hasToken && !TextUtils.isEmpty(TokenUtil.getToken())) {
            mHeaders.put(Global.TOKEN_TAG, String.format(Global.TOKEN_NAME_FORMAT_TAG, TokenUtil.getToken()));
        } else {
            mHeaders.remove(Global.TOKEN_TAG);
        }
        return mHeaders;
    }

    public static String createHttpUrl(Map<String, String> mParams, String mUrl, int method) {


        if (!mParams.isEmpty()) {
            StringBuilder url = new StringBuilder(mUrl);
            if (mParams.containsKey("id") && method != Request.Method.POST) {
                if (mUrl.endsWith("/")) {
                    url.append(mParams.get("id")).append("/");
                } else {
                    url.append("/").append(mParams.get("id")).append("/");
                }
            }
            if ((method == Request.Method.GET || method == Request.Method.DELETE) && mParams.size() > 0) {
                url.append("?");
                String temp = "%s=%s&";
                for (Map.Entry<String, String> entry : mParams.entrySet()) {
                    if (!TextUtils.isEmpty(entry.getValue()) && !"id".equals(entry.getKey())) {
                        url.append(String.format(temp, entry.getKey(), entry.getValue()));
                    }
                }
                return url.substring(0, url.length() - 1);
            }
            return url.toString();
        }
        return null;
    }
}
